package edu.ChildrensBooks.service

import edu.ChildrensBooks.model.Book

class BookService {


	boolean transactional = true

	boolean add(Book book) {
		if (book.save()) return true
		else return false
	}

	boolean update(Book book, Integer id) {
		Book theBook = Book.get(id)
		theBook.setAuthor(book.getAuthor())
		theBook.setTitle(book.getTitle())
		theBook.setIsbn(book.getIsbn())
		theBook.setMinGradeLevel(book.getMinGradeLevel())
		theBook.setMaxGradeLevel(book.getMaxGradeLevel())
		theBook.setDescription(book.getDescription())
		theBook.setLanguage(book.getLanguage())
		theBook.setCategory(book.getCategory())
		if (theBook.save()) return true
		else return false
	}

	boolean  delete(Integer id) {
		Book theBookToDelete = Book.get(id)
		if (theBookToDelete.delete()) return true
		else return false
	}

	Book getBook(String author, String bookTitle) {
		return Book.findByAuthorAndTitle(author, bookTitle);
	}

	Book getRandomBook() {
		def allBooks = Book.list()
		def randomBook = null
		if (allBooks.size() > 0) {
			def randomIdx = new Random().nextInt(allBooks.size())
			randomBook = allBooks[randomIdx]
		} else {
			return null
		}
		return randomBook
	}
}


